package com.lkx.farmershop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.common.properties.JwtProperties;
import com.lkx.farmershop.jwt.NewJwtUtil;
import com.lkx.farmershop.model.dto.LocationDto;
import com.lkx.farmershop.model.dto.LoginDTO;
import com.lkx.farmershop.model.dto.QueryObj;
import com.lkx.farmershop.model.entity.Farmer;
import com.lkx.farmershop.mapper.FarmerMapper;
import com.lkx.farmershop.model.vo.SimpleUserVo;
import com.lkx.farmershop.service.IFarmerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lkx
 * @since 2024-02-05
 */
@Service
@Slf4j
public class FarmerServiceImpl extends ServiceImpl<FarmerMapper, Farmer> implements IFarmerService {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public String executeRegister(Farmer farmer) {
        LambdaQueryWrapper<Farmer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Farmer::getPhoneNum, farmer.getPhoneNum());
        Farmer one = this.getOne(wrapper);
        if (!ObjectUtils.isEmpty(one)) {
            return "该手机号已注册";
        }
        LambdaQueryWrapper<Farmer> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Farmer::getName, farmer.getName());
        Farmer one1 = this.getOne(wrapper1);
        if (!ObjectUtils.isEmpty(one1)) {
            return "该用户昵称已存在";
        }
        boolean save = this.save(farmer);
        if (save) {
            return "账号注册成功";
        } else {
            return "账号注册失败，请稍后再试";
        }
    }

    @Override
    public String executeLogin(LoginDTO dto) {
        String token = null;
        try {
            Farmer farmer = lambdaQuery().eq(Farmer::getPhoneNum, dto.getPhoneNum()).one();

            String encodePwd = dto.getPassword();
            if (!encodePwd.equals(farmer.getPass())) {
                throw new Exception("密码错误");
            }
            //token = JwtUtil.generateToken(String.valueOf(farmer.getFarmerId()));
            // 创建token
            Map<String, Object> claims = new HashMap<>();
            Long farmerId = farmer.getFarmerId();
            claims.put("userId", farmerId);
            token = NewJwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claims);
        } catch (Exception e) {
            log.warn("用户不存在or密码验证失败=======>{}", dto.getPhoneNum());
        }
        return token;
    }

    @Override
    public ApiResult<List<SimpleUserVo>> searchUser(QueryObj queryObj) {
        List<Farmer> userList = lambdaQuery()
                .like(Farmer::getName, queryObj.getTheKeyWord())
                .last("LIMIT " + (queryObj.getPageNum() - 1) * queryObj.getPageSize() + ", " + queryObj.getPageSize())   // 只查10条
                .list();

        if (userList!=null && !userList.isEmpty()){
            List<SimpleUserVo> userVos = userList.stream().map(user -> {
                SimpleUserVo simpleUserVo = new SimpleUserVo();
                simpleUserVo.setUserId(user.getFarmerId());
                simpleUserVo.setUserName(user.getName());
                simpleUserVo.setAvatar(user.getAvatar());
                return simpleUserVo;
            }).collect(Collectors.toList());
            return ApiResult.success(userVos);
        }
        return ApiResult.failed("没有搜索到用户");
    }

    @Override
    public ApiResult<String> updateLocation(LocationDto locationDto) {
        Long userId = locationDto.getUserId();
        Farmer farmer = lambdaQuery().eq(Farmer::getFarmerId, userId).one();
        if (farmer!=null){
            farmer.setLongitude(locationDto.getLongitude());
            farmer.setLatitude(locationDto.getLatitude());
            farmer.setLocation(locationDto.getLocation());
            if (this.updateById(farmer)){
                return ApiResult.success("位置更新成功");
            }else {
                return ApiResult.failed("位置更新失败");
            }
        }else {
            return ApiResult.failed("请先登录");
        }
    }


}
